<?php

namespace app\admin\controller\kuerp\statistic;

use app\common\controller\Backend;
use app\admin\model\department\Admin;
use app\admin\model\kuerp\StaffMember as StaffMemberModel;
use app\admin\model\kuerp\CollectionSale;
use app\admin\model\kuerp\GoodsType;
use \app\admin\model\department\Department as DepartmentModel;
use app\admin\model\department\Admin as DepartmentAdmin;
use think\Db;
use fast\Tree;
/**
 * 回款报表
 *
 * @icon fa fa-circle-o
 */
class Collection extends Backend
{

    /**
     * Collection模型对象
     * @var \app\admin\model\kuerp\Collection
     */
    protected $model = null;
    protected $childrenSales = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kuerp\Collection;
        //部门经理查看部门成员 上级部门能查看下级部门
        $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
        //转为职员id
        $this->childrenSales = $adminids ? (new StaffMemberModel())->getStaffMemberIds($adminids) : [];

        $salelist = (new StaffMemberModel())->getSaleList($this->childrenSales);
        $this->view->assign("saleList", $salelist);
        $saleLists = [];
        foreach ($salelist as $salelist_k=>$salelist_v){
            $saleLists[] = ['name'=>$salelist_v['name'],'value'=>$salelist_v['id']];
        }
        $this->assignconfig("saleLists", $saleLists);

        // $tree = Tree::instance();
        // $tree->init(Admin::getAllDepartmentsArray($this->auth->id,($this->auth->isSuperAdmin()||$this->auth->data_scope)?true:false), 'parent_id');
        // $departmentList = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $orgindepartmentList = Admin::getAllDepartmentsTreeArray($this->auth->id, $this->auth->isSuperAdmin()||$this->auth->data_scope);
        $departmentList = [];
        foreach ($orgindepartmentList as $key => $value) {
            $departmentList[] = [
                'id' => $key,
                'name' => $value
            ];
        }
        $this->view->assign("departmentList", $departmentList);
    }
    
    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $department_auth = $this->auth->check('kuerp/statistic/staff_member/department');
            $where = [];
            $searchdata = input();
            if($searchdata){
                foreach ($searchdata as $k => &$v) {
                    if(!empty($v)){
                        if ($k=='sale_user'){
                            $where['staff_member_id'] = ['in', $v];
                        } else if ($k == 'times') {
                            $where['collection.purchase_time'] = ['between', setTimes($v,'time')];
                        } else if ($k == 'department_id') {
                            $departmentids = DepartmentModel::getChildrenIds($v, true);
                            $adminids = Admin::getDepartmentAdminIds($departmentids);
                            $sales = (new StaffMemberModel())->getStaffMemberIds($adminids);
                            $where['staff_member_id'] = ['in', $sales];
                        }
                    }
                }
            }
            if (!isset($where['staff_member_id']) && !$this->auth->isSuperAdmin()) {
                //部门经理查看部门成员 上级部门能查看下级部门
                $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
                //转为职员id
                if ($adminids) {
                    $sales = (new StaffMemberModel())->getStaffMemberIds($adminids);
                    $where['staff_member_id'] = ['in', $sales];
                }
            }
            
            $list = Db::name('kuerp_collection')
                ->alias('collection')
                ->where($where)
                ->field("staff_member_id,sum(write_off) as all_money")->group('staff_member_id')->select();
                // echo Db::name('kuerp_collection')->getLastSql();
            $data = [
                'name' => [],
                'price' => [],
                // 'number' => [],
            ];
            $count = [
                // 'number' => 0,
                'price' => 0
            ];
            $datelist = [
                'date' => [],
                'data' => [],
                'name' => [],
            ];
            if(!empty($list)){
                
                $sale_users = array_column($list,'staff_member_id');
                $stafflist = Db::name('kuerp_staff_member')->where(['id'=> ['in', $sale_users]])->column('name', 'id');
                //按日期 按销售员 group by purchase_time,sale_user 
                //根据日期天数 判断是按天， 月 group by purchase_time,sale_user
                if (!empty($searchdata['times']) && !in_array($searchdata['times'],['today','yesterday'])){
                    $times = setTimes($searchdata['times'],'time');
                    $days = ceil(($times[1]-$times[0])/86400);
                    $dates = [];
                    if($days <= 31){
                        $fields = 'staff_member_id,sum(write_off_price) as all_money,DATE_FORMAT(FROM_UNIXTIME(collection_sale.purchase_time), \'%Y%m%d\') as date,DATE_FORMAT(FROM_UNIXTIME(collection_sale.times), \'%Y%m\') as sale_month';
                        $start = strtotime(date('Y-m-d', $times[0]));
                        $end = strtotime(date('Y-m-d', $times[1]));
                        $dates = [];
                        for($i = $start; $i <= $end; $i += 86400) {
                            $dates[] = date('Ymd', $i);
                        }
                    }else {
                        $fields = 'staff_member_id,sum(write_off_price) as all_money, DATE_FORMAT(FROM_UNIXTIME(collection_sale.purchase_time), \'%Y%m\') as date,DATE_FORMAT(FROM_UNIXTIME(collection_sale.times), \'%Y%m\') as sale_month';
                        // 生成月份数组
                        $start = date('Ym', $times[0]);
                        $end = date('Ym', $times[1]); 
                        $dates = [];
                        while($start <= $end) {
                            $dates[] = $start;
                            $start = date('Ym', strtotime($start . '01 +1 month'));
                        }
                    }
                    $group = 'staff_member_id,date,sale_month';
                    $datelist['date'] = $dates;
                    $datelist['name'] = $stafflist;
                    $grouplist = (new CollectionSale())->with(['collection'])->where($where)->field($fields)->group($group)->order('date')->select();
                    // echo Db::name('kuerp_collection_sales')->getLastSql();
                    // dump($grouplist);
                    $newgrouplist = [];
                    foreach ($grouplist as $k=>$v){
                        $collection_month = substr($v['date'], 0, 6); // 提取回款月份(YYYYMM)
    
                        // 判断回款类型
                        $type = ($v['sale_month'] == $collection_month) 
                            ? 'current'  // 当月订单回款
                            : 'previous'; // 之前订单回款
                        
                        // 初始化数据结构
                        if (!isset($newgrouplist[$v['staff_member_id']][$v['date']])) {
                            $newgrouplist[$v['staff_member_id']][$v['date']] = [
                                'current'  => 0,
                                'previous' => 0
                            ];
                        }

                        $newgrouplist[$v['staff_member_id']][$v['date']][$type] += round($v['all_money'],2);
                    }
                    foreach ($stafflist as $stafflist_k=>$stafflist_v){
                        $datelist['data'][$stafflist_k] = [];
                        foreach ($dates as $dates_k=>$dates_v){
                            $datelist['data'][$stafflist_k][$dates_v] = $newgrouplist[$stafflist_k][$dates_v] ?? ['current'=>0,'previous'=>0];
                        }
                    }
                }
                //按部门统计
                if (empty($searchdata['department_id']) && ($department_auth || $this->auth->isSuperAdmin())) {
                    //获取部门信息
                    $departments = Db::name('department')->where(['status' => 'normal', 'tags' => '销售'])->field('id,name')->select();
                    $departments = collection($departments)->toArray();
                    //获取部门下员工信息
                    $departmentIds = DepartmentAdmin::getDepartmentGroupAdminIds(array_column($departments, 'id'));
                    $newlist = array_column($list, null, 'staff_member_id');
                    foreach ($departments as $k => $v) {
                        $data['name'][] = $v['name'];
                        $admin_ids = $departmentIds[$v['id']] ?? '';
                        $sales = (new StaffMemberModel())->getStaffMemberIds($admin_ids);
                        $price = $number = 0;
                        foreach ($sales as $sale) {
                            if (!empty($newlist[$sale])) {
                                $price += $newlist[$sale]['all_money'];
                                // $number += $newlist[$sale]['number'];
                            }
                        }
                        $data['price'][] = round($price, 2);
                        $data['number'][] = $number;
                        // $count['number'] += $number;
                        $count['price'] += $price;
                    }
                } else {
                    foreach ($list as $list_k=>$list_v){
                        $data['name'][] = $stafflist[$list_v['staff_member_id']] ?? '';
                        $data['price'][] = round($list_v['all_money'],2);
                        // $data['number'][] = $list_v['number'];
                        // $count['number'] += $list_v['number'];
                        $count['price'] += $list_v['all_money'];
                    }
                }
                $count['price'] = round($count['price'],2);
            }

            return json(['title' => '销售员回款统计分析', 'data' => $data, 'count' => $count, 'datelist' => $datelist]);
        }
        return $this->view->fetch();
    }

}
